/**
 * 报名表单提交功能
 * 使用multipart/form-data格式提交数据
 */
document.addEventListener('DOMContentLoaded', function () {
  const applicationForm = document.getElementById('application-form');
  if (applicationForm) {
    applicationForm.addEventListener('submit', handleEnrollSubmit);
  }
});

/**
 * 处理报名表单提交
 * @param {Event} event - 表单提交事件
 */
function handleEnrollSubmit(event) {
  event.preventDefault();
  console.log('表单提交事件触发'); // 添加调试日志

  // 验证表单
  if (!validateEnrollForm()) {
    console.log('表单验证失败'); // 添加调试日志
    showNotification('请完善所有必填信息', 'error');
    return;
  }

  // 收集表单数据
  const formData = collectFormData();
  console.log('收集到的表单数据:', formData); // 添加调试日志

  // 提交表单数据
  submitEnrollForm(formData)
    .then(response => {
      console.log('提交成功，响应数据:', response); // 添加调试日志
      showNotification('报名提交成功！', 'success');
      // 重置表单
      document.getElementById('application-form').reset();
    })
    .catch(error => {
      console.error('提交失败，错误信息:', error); // 添加调试日志
      showNotification(`提交失败: ${error.message}`, 'error');
    });
}

/**
 * 验证报名表单
 * @returns {boolean} 表单是否验证通过
 */
function validateEnrollForm() {
  let isValid = true;

  // 验证必填字段 - 与后端字段匹配
  const requiredFields = [
    'name', 'student-id', 'major', 'grade',
    'math-score', 'english-score', 'expertise',
     /**'application-time', **/'projectExperience',
    'futureDevelopment', 'email', 'phone'
  ];

  requiredFields.forEach(fieldId => {
    const field = document.getElementById(fieldId);
    if (!field.value.trim()) {
      setFieldError(field, '此字段为必填项');
      isValid = false;
    } else {
      clearFieldError(field);
    }
  });

  // 验证邮箱格式
  const emailField = document.getElementById('email');
  if (emailField.value.trim() && !isValidEmail(emailField.value)) {
    setFieldError(emailField, '请输入有效的邮箱地址');
    isValid = false;
  }

  // 验证手机号码（11位数字）
  const phoneField = document.getElementById('phone');
  if (phoneField.value.trim() && !isValidPhone(phoneField.value)) {
    setFieldError(phoneField, '请输入有效的11位手机号码');
    isValid = false;
  }

  // 验证意向方向至少选择一个
  const directionCheckboxes = document.querySelectorAll('[id^="direction-"]:checked');
  if (directionCheckboxes.length === 0 && !document.getElementById('direction-other').value.trim()) {
    showNotification('请至少选择一个意向方向', 'error');
    isValid = false;
  }

  return isValid;
}

/**
 * 收集表单数据并转换为FormData
 * @returns {FormData} 包含所有表单数据的FormData对象
 */
function collectFormData() {
  const formData = new FormData();

  // 基本信息 - 与后端字段完全匹配
  formData.append('name', document.getElementById('name').value.trim());
  formData.append('number', document.getElementById('student-id').value.trim());
  formData.append('major', document.getElementById('major').value.trim());
  formData.append('grade', document.getElementById('grade').value);
  formData.append('gaokao_math', document.getElementById('math-score').value.trim());
  formData.append('gaokao_english', document.getElementById('english-score').value.trim());
  formData.append('good_at', document.getElementById('expertise').value.trim());
  // formData.append('book_time', document.getElementById('application-time').value);

  // 项目经历和发展规划
  formData.append('experience', document.getElementById('projectExperience').value.trim());
  formData.append('other_lab', document.getElementById('otherLabRegistration').value.trim());
  formData.append('future', document.getElementById('futureDevelopment').value.trim());

  // 联系方式
  formData.append('email', document.getElementById('email').value.trim());
  formData.append('phone_number', document.getElementById('phone').value.trim());

  // 意向方向（组合选择的方向为字符串）
  const directions = [];
  document.querySelectorAll('[id^="direction-"]:checked').forEach(checkbox => {
    directions.push(checkbox.nextElementSibling.textContent.trim());
  });
  // 添加其他意向
  const otherDirection = document.getElementById('direction-other').value.trim();
  if (otherDirection) {
    directions.push(otherDirection);
  }
  formData.append('follow_direction', directions.join(';'));

  // 报名原因
  formData.append('reason', document.getElementById('applicationReason')?.value.trim() || '希望加入实验室学习和成长');

  return formData;
}

/**
 * 提交报名表单数据到后端
 * @param {FormData} formData - 表单数据
 * @returns {Promise} 包含响应结果的Promise
 */
async function submitEnrollForm(formData) {
  // 修改为正确的后端接口地址（与提供的示例一致）
  const apiUrl = 'http://192.168.1.172:8000/interview/apply/';

  try {
    console.log('准备提交到:', apiUrl); // 添加调试日志
    const response = await fetch(apiUrl, {
      method: 'POST',
      body: formData,
      redirect: 'follow', // 添加与示例一致的redirect参数
      // 不需要设置Content-Type，FormData会自动处理
    });

    // 先获取文本响应以便调试
    const responseText = await response.text();
    console.log('原始响应:', responseText);

    // 尝试解析为JSON
    let data;
    try {
      data = JSON.parse(responseText);
    } catch (e) {
      data = { message: responseText };
    }

    if (!response.ok) {
      throw new Error(data.message || `提交失败 (状态码: ${response.status})`);
    }

    if (data.success === false) {
      throw new Error(data.message || '报名提交失败，请稍后再试');
    }

    return data;
  } catch (error) {
    console.error('报名提交出错:', error);
    throw error;
  }
}

/**
 * 验证邮箱格式
 * @param {string} email - 邮箱地址
 * @returns {boolean} 是否为有效的邮箱格式
 */
function isValidEmail(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

/**
 * 验证手机号码格式
 * @param {string} phone - 手机号码
 * @returns {boolean} 是否为有效的手机号码格式
 */
function isValidPhone(phone) {
  const regex = /^1[3-9]\d{9}$/; // 标准11位手机号验证
  return regex.test(phone);
}

/**
 * 设置字段错误状态
 * @param {HTMLElement} field - 表单字段
 * @param {string} message - 错误信息
 */
function setFieldError(field, message) {
  field.classList.add('border-red-500');
  // 检查是否已有错误提示元素
  let errorElement = field.nextElementSibling;
  if (!errorElement || !errorElement.classList.contains('error-message')) {
    errorElement = document.createElement('p');
    errorElement.className = 'error-message text-red-500 text-sm mt-1';
    field.parentNode.appendChild(errorElement);
  }
  errorElement.textContent = message;
}

/**
 * 清除字段错误状态
 * @param {HTMLElement} field - 表单字段
 */
function clearFieldError(field) {
  field.classList.remove('border-red-500');
  const errorElement = field.nextElementSibling;
  if (errorElement && errorElement.classList.contains('error-message')) {
    errorElement.remove();
  }
}

/**
 * 显示通知消息
 * @param {string} message - 通知消息内容
 * @param {string} type - 通知类型：success/error/info
 */
function showNotification(message, type = 'info') {
  // 检查是否已有通知容器，如无则创建
  let notificationContainer = document.getElementById('notification-container');
  if (!notificationContainer) {
    notificationContainer = document.createElement('div');
    notificationContainer.id = 'notification-container';
    notificationContainer.style.position = 'fixed';
    notificationContainer.style.top = '20px';
    notificationContainer.style.right = '20px';
    notificationContainer.style.zIndex = '9999';
    document.body.appendChild(notificationContainer);
  }

  // 创建通知元素
  const notification = document.createElement('div');
  notification.className = `px-4 py-3 rounded-lg shadow-lg mb-2 flex items-center ${type === 'success' ? 'bg-green-50 text-green-800 border border-green-200' :
    type === 'error' ? 'bg-red-50 text-red-800 border border-red-200' :
      'bg-blue-50 text-blue-800 border border-blue-200'
    }`;

  // 添加图标
  const icon = document.createElement('i');
  icon.className = `mr-2 ${type === 'success' ? 'fa fa-check-circle' :
    type === 'error' ? 'fa fa-exclamation-circle' :
      'fa fa-info-circle'
    }`;
  notification.appendChild(icon);

  // 添加消息文本
  const text = document.createTextNode(message);
  notification.appendChild(text);

  // 添加到容器
  notificationContainer.appendChild(notification);

  // 显示动画
  notification.style.opacity = '0';
  notification.style.transform = 'translateY(-20px)';
  notification.style.transition = 'opacity 0.3s, transform 0.3s';

  setTimeout(() => {
    notification.style.opacity = '1';
    notification.style.transform = 'translateY(0)';
  }, 10);

  // 3秒后自动消失
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transform = 'translateY(-20px)';
    setTimeout(() => notification.remove(), 300);
  }, 3000);
}